package neptune.web.server.services.user;

import java.io.File;

import it.robertobifulco.ias.IAS;
import it.robertobifulco.ias.principalmanager.ImpossibleToIdentifyPrincipalException;
import it.robertobifulco.ias.principalmanager.Principal;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import neptune.manager.installation.Installator;
import neptune.web.client.services.SecurityException;
import neptune.web.client.services.user.LogInService;
import neptune.web.server.ApplicationManager;
import neptune.web.server.InitializationException;
import neptune.web.server.security.IASCreationException;
import neptune.web.server.security.SecurityHelper;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * 
 * @author Roberto Bifulco [info@RobertoBifulco.it] [RobertoBifulco.it]
 * @author Luigi Lorenzo Arpino [luigiarpino@yahoo.it]
 *
 */
public class LogInServiceImpl extends RemoteServiceServlet implements
		LogInService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8399150521321590163L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		/*
		String configFilePath = null;

		if (config.getInitParameter("configFilePath") != null) 
		{
			configFilePath = config.getInitParameter("configFilePath");
			if (!configFilePath.endsWith(File.separator)) 
			{
				configFilePath += File.separator;
			}
		} 
		else
		{
			configFilePath = "/home/oltremago/Sviluppo/emuPlugin"; //debug
		}
		*/
		String configFilePath=System.getProperty("user.home")+File.separator+".emuPlugin"+File.separator;
		ApplicationManager.setConfigFilePath(configFilePath);
		// Installo l'applicazione	
		String emuPluginSource = this.getServletContext().getRealPath("/WEB-INF/emuPlugin");
		Installator installator=new Installator();
		installator.install(emuPluginSource);
	}

	public String login(String username, String password)
			throws SecurityException {
		try {
			// Creazione del gestore dell'IAS per l'inizializzazione del
			// framework RBAC
			IAS ias = ApplicationManager.getApplicationManager().getIAS();

			Principal principal = ias.getPrincipal(username, password);

			// Crea la sessione utente
			HttpSession session = getThreadLocalRequest().getSession(true);
			SecurityHelper.setPrincipal(session, principal);

			return principal.getRole();
		} catch (ImpossibleToIdentifyPrincipalException e) {
			throw new SecurityException(e.getMessage());
		} catch (IASCreationException e) {
			e.printStackTrace();
			throw new SecurityException(e.getMessage());
		} catch (InitializationException e) {
			e.printStackTrace();
			throw new SecurityException(e.getMessage());
		}
	}

}
